package com.yungu.swift.autoconfig.lock;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.framework.recipes.locks.InterProcessReadWriteLock;
import org.apache.curator.framework.recipes.locks.InterProcessSemaphoreMutex;
import org.apache.curator.framework.recipes.locks.InterProcessSemaphoreV2;
import org.apache.curator.retry.ExponentialBackoffRetry;

/**
 * @author : cuixiuyin
 * @date : 2019/9/9
 */
public class ZkLock {

    private CuratorFramework client;

    public ZkLock(String zookeeper, String namespace) {
        client = CuratorFrameworkFactory.newClient(zookeeper, new ExponentialBackoffRetry(1000, 3));
        client.start();
        // 启用命名空间，做微服务间隔离
        client.usingNamespace(namespace);

    }

    /**
     * 可重入排他锁
     *
     * @param lockPath 路径 /zk
     * @return
     */
    public InterProcessMutex interProcessMutex(String lockPath) {
        return new InterProcessMutex(client, lockPath);
    }

    /**
     * 不可重入排他锁
     *
     * @param lockPath 路径 /zk
     * @return
     */
    public InterProcessSemaphoreMutex interProcessSemaphoreMutex(String lockPath) {
        return new InterProcessSemaphoreMutex(client, lockPath);
    }


    /**
     * 分布式读写锁
     *
     * @param lockPath 路径 /zk
     * @return
     */
    public InterProcessReadWriteLock interProcessReadWriteLock(String lockPath) {
        return new InterProcessReadWriteLock(client, lockPath);
    }


    /**
     * 共享信号量 —— 设置最大并行数量
     *
     * @param lockPath  路径 /zk
     * @param semaphore 最大允许访问的数量
     * @return
     */
    public InterProcessSemaphoreV2 interProcessSemaphore(String lockPath, int semaphore) {
        return new InterProcessSemaphoreV2(client, lockPath, semaphore);
    }


}
